package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleMapper;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import com.itheima.utils.IdWorker;
import com.itheima.utils.Result;
import com.itheima.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private IdWorker idWorker;
    @Override
    public Role findRoleById(String roleUid) {
        return roleMapper.selectByPrimaryKey(roleUid);
    }


    //新增角色信息
    @Override
    public int add(Role role) {
        //查询角色名是否存在，存在则无法添加
        Role role1 = new Role();
        role1.setRoleName(role.getRoleName());
        Role role2 = roleMapper.selectOne(role1);
        if (role2 !=null){
            return 0;
        }

        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        role.setUid(String.valueOf(idWorker.nextId()));
        role.setStatus(1);

        int i = roleMapper.insert(role);
        return i;
    }

    //删除
    @Override
    public Result delete(Role role) {
        roleMapper.delete(role);

        return new Result<>(StatusCode.SUCCESS,"删除成功");
    }

    //编辑
    @Override
    public Result edit(Role role) {
        Role roleOne = roleMapper.selectByPrimaryKey(role.getUid());
        if (roleOne==null){
            return new Result<>(StatusCode.FAIL,"没有数据，无法修改");
        }
        role.setUpdateTime(new Date());
         roleMapper.updateByPrimaryKeySelective(role);
        return new Result<>(StatusCode.SUCCESS,"编辑成功");
    }

    //分页
    @Override
    public Page<Role> getList(Role role) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        if (role.getKeyword() != null && !role.getKeyword().equals("")) {
            criteria.andLike("roleName", "%"+role.getKeyword()+"%");
        }
        PageHelper.startPage(role.getCurrentPage(),role.getPageSize());
        List<Role> roleList = roleMapper.selectByExample(example);

        return (Page<Role>) roleList;


    }

  @Override
    public void update(Role role) {
        roleMapper.updateByPrimaryKeySelective(role);
    }
}
